package com.sz.common.core.system.utils;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: qiankun<br>
 * Date: 2017-07-19 18:01:00
 */
public class PDFUtils {

    public static String getPdfUploadUrl(String content, FastFileStorageClient storageClient) throws FileNotFoundException, DocumentException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ITextRenderer render = new ITextRenderer();
        render.setDocumentFromString(content);
        render.layout();
        render.createPDF(os);
        ByteArrayInputStream swapStream = new ByteArrayInputStream(os.toByteArray());
        StorePath storePath = storageClient.uploadFile(swapStream, os.toByteArray().length,
                "pdf", null);
        return storePath.getFullPath();
    }

    public static OutputStream getPdfStream(String content) throws IOException, DocumentException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        ITextRenderer render = null;
        try {
            render = new ITextRenderer();
        } catch (Throwable e) {
            render = new ITextRenderer();
        }

        ITextFontResolver fontResolver = render.getFontResolver();
        Resource resource = new ClassPathResource(File.separator + "templates");
        String path = resource.getFile().getPath();
        path = path + File.separator + "simsun.ttf";
        fontResolver.addFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        render.setDocumentFromString(content);
        render.layout();
        render.createPDF(os);
        os.flush();
        os.close();
        return os;
    }

}
